package org.dydl.common.security.url;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dydl.model.system.SysRights;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Service;

/**
 * 
 * @Description:最核心的地方，就是提供某个资源对应的权限定义，即getAttributes方法返回的结果
 * @Copyright: Copyright (c) 2017 Yorma All Rights Reserved
 * @Company: 济南悦码信息科技有限公司
 * @author DWL 2017年10月27日
 * @version 1.00.00
 * @history:
 *
 */
@Service
public class UrlMetadataSourceService implements FilterInvocationSecurityMetadataSource {

	// @Reference
	// private ISysRightsService sysRightsService;

	@SuppressWarnings("unused")
	private static final Logger logger = LoggerFactory.getLogger(UrlMetadataSourceService.class);

	/**
	 * 资源集合
	 */
	private static Map<SysRights, Collection<ConfigAttribute>> sysRightsMap = null;

	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		// 当资源为空时，进行加载资源列表
		// if (sysRightsMap == null)
		// loadSysRightsDefine();

		if (sysRightsMap == null)
			sysRightsMap = new HashMap<>();

		FilterInvocation filterInvocation = (FilterInvocation) object;
		for (SysRights sysRights : sysRightsMap.keySet()) {
			RequestMatcher requestMatcher = new AntPathRequestMatcher(sysRights.getUrl());
			HttpServletRequest httpRequest = filterInvocation.getHttpRequest();
			if (requestMatcher.matches(httpRequest))
				return sysRightsMap.get(sysRights);
		}
		return null;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

	// @SuppressWarnings("unchecked")
	// private void loadSysRightsDefine() {
	// if(sysRightsService==null)
	// return;
	// // 1.加载出所有的请求资源
	// Search search = new Search();
	// search.addFilterEqual("resType", "2");
	// ResponseMessage responseMessage = sysRightsService.search(search);
	// // 若查询结果为false，终止操作
	// if (!responseMessage.getSuccess()) {
	// if (logger.isErrorEnabled())
	// logger.error("调用远程服务查询权限资源失败");
	// return;
	// }
	// sysRightsMap = new HashMap<>();
	// List<SysRights> sysRightsList = (List<SysRights>) responseMessage.getData();
	// for (SysRights sysRights : sysRightsList) {
	// // 避免出现新加入的请求URL没有任何角色权限出现正常访问的情况，默认会赋予新加入的请求资源无权限
	// if (!sysRightsMap.containsKey(sysRights)) {
	// Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
	// ConfigAttribute ca = new SecurityConfig("无权限");
	// atts.add(ca);
	// sysRightsMap.put(sysRights, atts);
	// }
	// // 取角色
	// responseMessage =
	// sysRightsService.getSysRoleByRightId(sysRights.getId().toString());
	// // 若查询结果为false，终止操作
	// if (!responseMessage.getSuccess()) {
	// if (logger.isErrorEnabled())
	// logger.error("调用远程服务查询权限角色失败");
	// return;
	// }
	// List<SysRole> sysRoleList = (List<SysRole>) responseMessage.getData();
	// for (SysRole sysRole : sysRoleList) {
	// ConfigAttribute ca = new SecurityConfig(sysRole.getName());
	// // 判断资源文件和权限的对应关系，如果已经存在相关的资源URL，则要通过该URL为key提取出权限集合，将权限增加到权限集合中
	// Collection<ConfigAttribute> value = sysRightsMap.get(sysRights);
	// value.add(ca);
	// sysRightsMap.put(sysRights, value);
	// }
	// }
	// if (logger.isInfoEnabled())
	// logger.info("--------------------------------初始化资源列表完成--------------------------------");
	// }

	/**
	 * 清空当前集合信息(容易出现并发问题)
	 */
	public static void clearSysRightMap() {
		if (null != sysRightsMap) {
			sysRightsMap.clear();
			sysRightsMap = null;
		}
	}

}
